<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;

class Channel extends Model
{
    use HasFactory, SoftDeletes;

    const GATEWAY_WECHAT = 'wxpay';
    const GATEWAY_QQPAY = 'qqpay';
    const GATEWAY_ALIPAY = 'alipay';

    public static $gatewayMap = [
        self::GATEWAY_WECHAT => '微信',
        self::GATEWAY_QQPAY => 'QQ',
        self::GATEWAY_ALIPAY => '支付宝',
    ];

    const MODE_NORMAL = 'normal';
    const MODE_SERVICE = 'service';

    public static $modeMap = [
        self::MODE_NORMAL => '普通模式',
//        self::MODE_SERVICE => '服务商模式'
    ];

    const STATUS_NORMAL = 'normal';
    const STATUS_STOPPED = 'stopped';
    // 状态
    public static $statusMap = [
        self::STATUS_NORMAL => '正常',
        self::STATUS_STOPPED => '停用',
    ];

    protected $fillable = [
        'name', 'rate', 'gateway', 'mode', 'status', 'method', 'mch_id', 'mch_key', 'mp_appid', 'mp_secret', 'mini_appid', 'mini_secret', 'public_key', 'private_key'
    ];

    public static function random($gateway)
    {
        $info = self::query()
            ->where('gateway', $gateway)
            ->where('status', self::STATUS_NORMAL)
            ->get()->toArray();
        return Arr::random($info, 1);
    }

    public function getMethodAttribute($value)
    {
        return json_decode($value, true);
    }

    public function setMethodAttribute($value)
    {
        $this->attributes['method'] = json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}
